import React from 'react';
import { Button, Icon, message } from 'antd';
import { toJS } from 'mobx';
import { WeaLocaleProvider, WeaTools, WeaDialog, WeaMoreButton, WeaSearchGroup, WeaFormItem, WeaInput, WeaSelect, WeaCheckbox, WeaTextarea, WeaTable, WeaBrowser, WeaHelpfulTip } from 'ecCom';
import { HotTable } from '@handsontable/react';
import 'handsontable/languages/zh-CN';
import 'handsontable/languages/zh-TW';
import { WeaPortalStyleBrowser } from 'weaPortalPublic';
import Content_RankingList_SqlTemplateManage from './Content_RankingList_SqlTemplateManage';

const getLabel = WeaLocaleProvider.getLabel;

// 排行榜，数据来源
class Content_RankingList_DataSource extends React.Component {
  constructor(props) {
    super(props);
    const { tabData = {}, tabNew = {} } = props;
    this.state = {
      id: tabData.id,
      title: tabData.title,
      styleType: tabData.styleType || '1',
      moreUrl: tabData.moreUrl || '',
      dataFrom: tabData.dataFrom || tabNew.dataFrom.selected,
      dataSource: tabData.dataSource || tabNew.dataSource.selected,
      sql: tabData.sql || '',
      saveToTemplate: false,
    };
  }

  render() {
    const { tabNew } = this.props;
    const { title, styleType, moreUrl, dataFrom, dataSource, sql, saveToTemplate } = this.state;
    const colProps = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };

    const styleTypes = [
      {
        id: '1',
        name: getLabel(519638, '勋章列表'),
        filepath: '/spa/portal/images/rankinglist/s01.jpg',
      },
      {
        id: '2',
        name: getLabel(519639, '奖杯样式'),
        filepath: '/spa/portal/images/rankinglist/s02.jpg',
      },
      {
        id: '3',
        name: getLabel(519640, '奖牌样式'),
        filepath: '/spa/portal/images/rankinglist/s03.jpg',
      },
      {
        id: '4',
        name: getLabel(519641, '普通列表'),
        filepath: '/spa/portal/images/rankinglist/s04.jpg',
      },
    ];

    const hasSQLRight = tabNew.dataFrom.hasSQLRight;
    const dataFromOptions = [];
    tabNew.dataFrom.options.forEach(item => dataFromOptions.push({ key: item.key, selected: false, showname: item.value }));
    const dataSourceOptions = [];
    tabNew.dataSource.options.forEach(item => dataSourceOptions.push({ key: item.key, selected: false, showname: item.value }));

    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@xbskzw`}
        visible={true}
        title={getLabel(19480, '内容设置')}
        icon="icon-coms-portal"
        iconBgcolor="#1a57a0"
        style={{ width: 800, height: 591 }}
        hasScroll={true}
        buttons={this.getButtons()}
        onCancel={this.onCancel}
      >
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@4y3vi2`} title={getLabel(33396, '设置项')} showGroup={true} center={true}>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@caawk0`} label={getLabel(24986, '标题')} {...colProps}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@nsmkuj`} inputType="multilang" isBase64={true} value={title} viewAttr={3} onChange={value => this.setState({ title: value })} />
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@xsu7ig`} label={getLabel(519642, '排行榜样式')} {...colProps}>
            <WeaPortalStyleBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaPortalStyleBrowser@dhrbrn`} title={getLabel(519643, '选择排行榜样式')} itemData={styleTypes} value={styleType} onChange={value => this.setState({ styleType: value })} />
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4c4xrt`} label={getLabel(386563, 'More地址')} {...colProps}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@mkq1yj`} value={moreUrl} onChange={value => this.setState({ moreUrl: value })} />
            <div style={{ position: 'absolute', top: '6px', right: '-22px' }}>
              <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@gimsra`} title={getLabel(386567, '外部地址，请在地址前加上http://或https://')} />
            </div>
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@d3i93z`} label={getLabel(519644, '数据来源')} {...colProps}>
            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@5yajag`} options={dataFromOptions} value={dataFrom} viewAttr={hasSQLRight ? 2 : 1} onChange={value => this.setState({ dataFrom: value })} />
          </WeaFormItem>
          {hasSQLRight && dataFrom == '2' && (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@7t4kev`} label={getLabel(519645, '数据源')} {...colProps}>
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@0yr9r2`} options={dataSourceOptions} value={dataSource} onChange={value => this.setState({ dataSource: value })} />
            </WeaFormItem>
          )}
          {hasSQLRight && dataFrom == '2' && (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@h09z2b`} label={getLabel(519646, '自定义SQL')} {...colProps}>
              <div className="portal-esetting-rankinglist-sqltemplate">
                <div style={{ display: 'inline-block', marginRight: 12 }}>
                  <span style={{ paddingRight: 5 }}>{getLabel(127215, '保存到模板库')}</span>
                  <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@orny0s`} helpfulTip={getLabel(390861, '是否保存到模板库')} style={{ marginTop: 0, marginRight: 35 }} onChange={() => this.setState({ saveToTemplate: !saveToTemplate })} />
                </div>
                <span className="portal-esetting-rankinglist-sqltemplate-btn" onClick={() => this.sp4r.onShow()}>
                  {getLabel(33749, '系统变量')}
                </span>
                <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@hlcvcf`}
                  title={getLabel(386596, 'SQL模板')}
                  type="rankinglistsqltemplate"
                  isSingle={true}
                  hasAdvanceSerach={true}
                  icon="icon-coms-portal"
                  iconBgcolor="#1a57a0"
                  customized={true}
                  onChange={(ids, names, datas) => this.setState({ sql: datas[0] ? datas[0].rankinglistsql : '' })}
                >
                  <span className="portal-esetting-rankinglist-sqltemplate-btn">{getLabel(386596, 'SQL模板')}</span>
                </WeaBrowser>
                <span className="portal-esetting-rankinglist-sqltemplate-btn" onClick={() => this.stm.onShow()}>
                  <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@3kysv1`} type="setting" title={getLabel(388014, 'sql模板管理')} />
                </span>
              </div>
              <WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@7uivar`} value={sql} minRows={5} onChange={value => this.setState({ sql: value })} />
              <SynergyParams4Report ecId={`${this && this.props && this.props.ecId || ''}_SynergyParams4Report@yla5a5`} ref={sp4r => (this.sp4r = sp4r)} />
              <Content_RankingList_SqlTemplateManage ecId={`${this && this.props && this.props.ecId || ''}_Content_RankingList_SqlTemplateManage@a5utae`} ref={stm => (this.stm = stm)} />
            </WeaFormItem>
          )}
        </WeaSearchGroup>
        {dataFrom == '1' && (
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@fctyo1`}
            title={
              <div>
                <span style={{ marginRight: 10 }}>{getLabel(519647, '排行榜数据')}</span>
                <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@3s5res`}
                  title={
                    <div>
                      <div>{getLabel(519648, '可直接复制粘贴表格至下方区域。')}</div>
                      <div>{getLabel(519649, '添加/删除行、添加/删除列，均可通过右键进行操作。')}</div>
                      <div>{getLabel(519650, '请至少提供4行2列的表格数据，系统读取手动录入的排行榜数据时，名次根据列表顺序自动生成（1、2、3……），第一行数据会作为排行榜列头显示。')}</div>
                    </div>
                  }
                />
              </div>
            }
            showGroup={true}
          >
            <div id="portal-esetting-rankinglist-hottable">
              <HotTable ecId={`${this && this.props && this.props.ecId || ''}_HotTable@kbomlb`}
                ref={hottable => (this.hottable = hottable)}
                data={this.getHotTableData()}
                language={this.getHotTableLanguage()}
                colHeaders={true}
                rowHeaders={true}
                width={'100%'}
                height={300}
                startRows={11}
                startCols={4}
                minRows={11}
                minCols={4}
                colWidths={170}
                manualRowMove={true}
                manualColumnMove={true}
                fixedRowsTop={1}
                contextMenu={['row_above', 'row_below', '---------', 'col_left', 'col_right', '---------', 'remove_row', 'remove_col', '---------', 'copy', 'cut']}
                afterChange={(changes, source) => source != 'loadData' && this.onHotTableChange()}
                afterRowMove={this.onHotTableChange}
                afterColumnMove={this.onHotTableChange}
              />
            </div>
          </WeaSearchGroup>
        )}
      </WeaDialog>
    );
  }

  getButtons = () => {
    const buttons = [];
    buttons.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4c5wee`} type="primary" onClick={this.onOk}>
        {getLabel(30986, '保存')}
      </Button>,
    );
    buttons.push(<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@zk45hs`} datas={this.getRightMenus()} />);
    return buttons;
  };

  getRightMenus = () => {
    const rightMenus = [];
    rightMenus.push({ key: '1', icon: <i className="icon-coms-Preservation" />, content: getLabel(30986, '保存'), onClick: this.onOk });
    return rightMenus;
  };

  getHotTableData = () => {
    if (this.tableData) {
      return this.tableData;
    }
      const { tabData = {} } = this.props;
      let { tableData } = tabData;
      if (tableData) {
        if (typeof tableData == 'string') {
          tableData = JSON.parse(tableData);
        } else if (typeof tableData == 'object') {
          tableData = toJS(tableData);
        }
      } else {
        tableData = [
          ['排行对象', '排行数据'],
          ['对象1', '123万'],
          ['对象2', '122万'],
          ['对象3', '121万'],
          ['对象4', '121万'],
          ['对象5', '121万'],
        ];
      }
      this.tableData = tableData;
      return tableData;
  };

  getHotTableLanguage = () => {
    const languageidweaver = WeaTools.ls.getJSONObj('languageidweaver');
    if (languageidweaver == 7) {
      return 'zh-CN';
    } else if (languageidweaver == 9) {
      return 'zh-TW';
    }
      return 'en-US';
  };

  onHotTableChange = () => {
    const tableData = this.hottable.hotInstance.getData();
    this.tableData = tableData;
  };

  onOk = () => {
    const { title, dataFrom, saveToTemplate, sql: rankinglistsql } = this.state;

    if (!title) {
      message.warning(getLabel(15859, '必要信息不完整！'));
    } else if (dataFrom == '2' && saveToTemplate) {
        WeaTools.callApi('/api/portal/rankinglist/addSqlTemplate', 'POST', { title, rankinglistsql }).then((result) => {
          if (result.api_status) {
            message.success(getLabel(83551, '保存成功！'));
            this.props.onOk(this.state);
          } else {
            message.error(result.api_errormsg);
          }
        });
      } else {
        const tabData = this.state;
        if (dataFrom == '1') {
          tabData.tableData = this.tableData;
        }
        this.props.onOk(tabData);
      }
  };

  onCancel = () => {
    this.props.onCancel();
  };
}

export default Content_RankingList_DataSource;

class SynergyParams4Report extends React.Component {
  constructor(props) {
    super(props);
    this.state = { visible: false, loading: false, data: [] };
  }

  render() {
    const { visible, loading, data } = this.state;

    const columns = [
      { key: 'paramName', title: getLabel(386542, '变量名'), dataIndex: 'paramName', width: '50%' },
      { key: 'paramShowName', title: getLabel(386543, '变量显示名'), dataIndex: 'paramShowName', width: '25%' },
      { key: 'paramType', title: getLabel(386544, '变量类型'), dataIndex: 'paramType', width: '25%' },
    ];

    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@xavv8c`}
        visible={visible}
        loading={loading}
        title={getLabel(33749, '系统变量')}
        icon="icon-coms-synergism"
        iconBgcolor="#1a57a0"
        style={{ width: 500, height: 460 }}
        buttons={this.getButtons()}
        onCancel={this.onCancel}
      >
        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@64mj1e`} columns={columns} dataSource={data} pagination={false} />
      </WeaDialog>
    );
  }

  getButtons = () => {
    const buttons = [];
    buttons.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@f8sa0a`} type="ghost" onClick={this.onCancel}>
        {getLabel(309, '关闭')}
      </Button>,
    );
    return buttons;
  };

  onShow = () => {
    this.setState({ visible: true, loading: true });
    WeaTools.callApi('/api/portal/synergy/getReportParams', 'GET').then((result) => {
      this.setState({ loading: false, data: result.data });
    });
  };

  onCancel = () => {
    this.setState({ visible: false, data: [] });
  };
}
